import Cookies from 'js-cookie'
import store from '@/store'
import moment from 'moment'
import _ from 'lodash'
/**
 * @param {*} key
 */
export function hasPermission(key) {
  return window.SITE_CONFIG['permissions'].indexOf(key) !== -1 || false
}

/**
 * @param dictType
 */
export function getDictDataList(dictType) {
  const type = window.SITE_CONFIG['dictList'].find(
    element => element.dictType === dictType
  )
  if (type) {
    return type.dataList
  } else {
    return []
  }
}
/**
 * @param routerName
 */
export function hasPermissionRouterName(routerName) {
  return true
  // var array = this.$store.getters.menus
  // var key = 'name'
  // var o
  // routerName.replace(/ /g, '')
  // array.some(function iter (a) {
  //   if (a[key].toLowerCase() === routerName.toLowerCase() || a[key].replace(/ /g, '').toLowerCase() === routerName.toLowerCase()) {
  //     o = a
  //     return true
  //   }
  //   return Array.isArray(a.children) && a.children.some(iter)
  // })
  // return !!o
}
/**
 * @param dictType
 * @param dictValue
 */
export function getDictLabel(dictType, dictValue) {
  const type = window.SITE_CONFIG['dictList'].find(
    element => element.dictType === dictType
  )
  if (type) {
    const val = type.dataList.find(
      element => element.dictValue === dictValue + ''
    )
    if (val) {
      return val.dictLabel
    } else {
      return dictValue
    }
  } else {
    return dictValue
  }
}

export function clearLoginInfo() {

  Cookies.remove('token')
  Cookies.remove('tenant_code')
  if (Cookies.get('loginSource')) {
    Cookies.remove('loginSource')
  }

  window.sessionStorage.clear()
  window.localStorage.clear()
}

export function rememberRoute(router) {
  window.SITE_CONFIG['routerWithForgetToken'] = router
}

export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16)
  })
}
export function getLeijia(arr) {
  var arr2 = arr.map((item, index) => {
    var array = JSON.parse(JSON.stringify(arr)).splice(0, index + 1)
    return sum(array)
  })

  function sum(arr) {
    var res = 0
    arr.forEach(item => {
      res = Number(res) + Number(item)
    })
    return res
  }
  return arr2
}

export function getLeijias(arr) {
  var arr2 = arr.map((item, index) => {
    var array = JSON.parse(JSON.stringify(arr)).splice(0, index + 1)
    return sum(array, item)
  })

  function sum(arr, item) {
    var res = 0
    arr.forEach(item => {
      res = Number(res) + Number(item.value)
    })
    return {
      value: res,
      itemStyle: item.itemStyle
    }
  }
  return arr2
}

export function randomString() {
  let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  let tmp = ''
  let i = 0
  let l = str.length
  for (i = 0; i < 8; i++) {
    tmp += str.charAt(Math.floor(Math.random() * l))
  }
  return tmp
}

export function getIconList() {
  var res = []
  var list = document.querySelectorAll('svg symbol')
  for (var i = 0; i < list.length; i++) {
    res.push(list[i].id)
  }

  return res
}

/**
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate(data, id = 'id', pid = 'pid') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (!temp[data[k][pid]] || data[k][id] === data[k][pid]) {
      res.push(data[k])
      continue
    }
    if (!temp[data[k][pid]]['children']) {
      temp[data[k][pid]]['children'] = []
    }
    temp[data[k][pid]]['children'].push(data[k])
    data[k]['_level'] = (temp[data[k][pid]]._level || 0) + 1
  }
  return res
}

/**
 * @param {*} data
 */
export function copyData(data) {
  const url = data
  const oInput = document.createElement('input')
  document.body.appendChild(oInput)
  oInput.value = url
  oInput.select()
  document.execCommand('Copy')
  oInput.remove()
}


/**
 * Set Login Path
 *  @param  {String} path
 */
export function setLoginPath(path) {
  store.commit('SET_LOGIN_PATH', path)
}
/**
 * get TimeZone Name List
 */
export function TimeZoneNameList() {
  let arr = []
  let excludeList = getDictDataList('exclude_timezoneid_list')
    ? getDictDataList('exclude_timezoneid_list')
    : []
  let temp = []
  for (let i = 0; i < excludeList.length; i++) {
    const ele = excludeList[i]
    temp.push(ele.dictValue)
  }
  arr = _.pullAll(moment.tz.names(), _.uniq(temp))
  return arr
}
/**
 * get integration subjectCode with name
 * @param {String} data Name
 */
export async function findSubjectCodeWithName(data) {
  if (!window.SITE_CONFIG['dictList']) {
    await loadFun()
  }

  let psaList = _.filter(
    window.SITE_CONFIG['dictList'].find(e => e.dictType === 'integration_list')
      .dataList,
    { dictLabel: 'name' }
  )
  return _.filter(psaList, { dictValue: data })[0].subjectCode
}

export async function loadFun() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, 2000)
  })
}

export function stringRemoveSpaceEqual(str1 = '', str2 = '') {
  return (
    _.toUpper(str1.replace(/\s*/g, '')) === _.toUpper(str2.replace(/\s*/g, ''))
  )
}

export function loginSourcePathURL() {
  let tempSource = 'login'
  if (Cookies.get('loginSource') === 'login') {
    tempSource = 'login'
  }
  if (Cookies.get('loginSource') === 'emaillogin') {
    tempSource = 'emaillogin'
  }
  if (Cookies.get('loginSource') === 'portal') {
    tempSource = 'loginAsAccount'
  }
  return tempSource
}


/**
 * @param  {String} str
 */
export function themeName (str) {
  let temp = ''
  switch (str) {
    case 'echarts-dark':
      temp = 'dark'
      break
    default:
      temp = 'light'
      break
  }
  return temp
}